# 从flask框架中导入Flask类
from flask import Flask, jsonify, url_for, request, redirect, render_template
import Config
import json
from api.User import bp as user_bp

# 传入__name__初始化一个Flask实例
app = Flask(__name__)
app.register_blueprint(user_bp)
# flask 配置
app.config.from_object(Config)


# app.route装饰器映射URL和执行的函数。这个设置将根URL映射到了hello_world函数上
@app.route('/')
def hello_world():
    return {'country': '中国'}


books = [
    {"id": 1, "name": "三国演义"},
    {"id": 2, "name": "水浒传"},
    {"id": 3, "name": "西游记"},
    {"id": 4, "name": "红楼梦"}
]


@app.route('/book_list', methods=['GET', 'POST'])
def book_list():
    print(type({"id": 1, "name": "三国演义"}, ))
    # return json.dumps(books, ensure_ascii=False), 200, {"Content-Type": "application/json"}
    for book in books:
        book["url"] = url_for("book_by_id", book_id=book["id"])
        book["user_url"] = url_for("user.profile")
    return jsonify(books)
    # return str(books), 200, {"Content-Type": "application/json"}


@app.route('/book/detail/<int:book_id>')
def book_by_id(book_id):
    for book in books:
        if book["id"] == book_id:
            return book
    return f"根据 {book_id} 没有找到书籍"


@app.route("/profile")
def profile():
    user_id = request.args.get("id")
    if user_id:
        return "个人中心"
    else:
        return redirect(url_for("login"))


@app.route("/login")
def login():
    return "登陆界面"


@app.route("/about")
def about():
    context = {
        'username': '北大',
        'books': ['三国', '水浒'],
        'age':20
    }
    return render_template("about.html", **context)


if __name__ == '__main__':
    # 运行本项目，host=0.0.0.0可以让其他电脑也能访问到该网站，port指定访问的端口。默认的host是127.0.0.1，port为5000
    app.run(host='0.0.0.0', port=9000)
